import { Context } from 'egg';
// import { Op } from 'sequelize';
import flat from 'lodash/flatten'
export default (action?: string) => async (ctx: Context, next) => {


  // 开发模式跳过权限检查
  const { config } = ctx.app;
  if (config.skipAuthentication) {
    await next();
    return true;
  }
  const userInfo = ctx.state.user;
  const responseData = { userId: userInfo, uri: action };

  if (ctx.state && ctx.state.user && ctx.state.user.shop_id) {
    ctx._shop = {
      id: ctx.state.user.shop_id
    }
  }
  if (!action) {
    await next();
    return;
  }

  const user = await ctx.model.AuthUser.findOne({
    where: { id: userInfo.id },
    include: [
      {
        model: ctx.model.AuthGroup,
        include: {
          model: ctx.model.AuthModule
        }
      }
    ],
  });

  const authGroups = user?.auth_groups || [];
  const authModules = flat(authGroups.map(it => it.auth_modules || []));
  //@ts-ignore
  const modelUri = authModules.map(it => it.uri);
  if (!modelUri.includes(action)) {
    ctx.forbidden({ data: responseData });
    return false;
  }
  await next();
  return true;
};
